

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Widget)
    widget: cc.Widget = null;

    @property(cc.Label)
    label: cc.Label = null;

    @property(cc.Node)
    bg: cc.Node = null;

    @property(cc.Node)
    bar: cc.Node = null;

    @property(cc.Color)
    colorList: cc.Color[] = [];

    private progress = 0;

    public init(progress) {
        this.progress = progress;

        this.bar.anchorX = 0;
        this.bar.x = -this.bg.width / 2;

        this.updateUI();

    }

    private updateUI() {
        //进度
        this.bar.width = Math.floor(this.progress * this.bg.width);

        //显示百分比
        this.label.string = `${Math.trunc(this.progress * 100)}%`;

        //设置lable对齐
        let minWidth = 80;
        if (this.bar.width < minWidth) {
            this.widget.right = -minWidth - 20;
            this.label.node.color = new cc.Color(140, 41, 25)
        } else {
            this.widget.right = 20;
            this.label.node.color = new cc.Color(255, 255, 255)
        }

        //设置颜色
        let index = Math.floor(this.colorList.length * this.progress);
        index = index == this.colorList.length ? index - 1 : index;
        this.bar.color = this.colorList[index];

        this.widget.updateAlignment();
    }

}
